//
//  TravelNotesHomePageViewController.m
//  旅游咨询
//
//  Created by 徐斌 on 15/4/15.
//  Copyright (c) 2015年 xubin. All rights reserved.
//

#import "TravelNotesHomePageViewController.h"



@interface TravelNotesHomePageViewController ()


@end

@implementation TravelNotesHomePageViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // 创建collectionview
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(WidthZ , WidthZ * 3 / 4);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.headerReferenceSize = CGSizeMake(HeighZ * 0.015, 0);

    
//    [[DataHandle sharDataBaseHandle]openDBb];
    
    self.navigationItem.title = @"游记";
    
    flowLayout.sectionInset = UIEdgeInsetsMake(HeighZ * 0.6, 5, 0, 0);
    
    UICollectionView *myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64) collectionViewLayout:flowLayout];
    myCollectionView.delegate = self;
    myCollectionView.dataSource = self;
    myCollectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:myCollectionView];
    
//    [[DataHandle sharDataBaseHandle]openDB];
//    [[DataHandle sharDataBaseHandle]creatDB];
    
    [myCollectionView registerClass:[TravelNotesHomePageCollectionViewCell class]forCellWithReuseIdentifier:@"reuse"];
    [myCollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    
    myCollectionView.bounces = NO;
    
//    self.imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 335, 30, 30)];
//    self.imageV.image = [UIImage imageNamed:@"auth_login_register_indicator@2x~ipad.png"];
    // 更多button
//    self.moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    
//    [self.moreButton setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
//    
//    
////    self.moreButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
////    self.moreButton.contentEdgeInsets = UIEdgeInsetsMake( 0, 0, 0, 20);
//    
//  
////    [self.moreButton addSubview:hotlabel];
//    [self.moreButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    self.moreButton.frame = CGRectMake(0, flowLayout.sectionInset.top - HeighZ * 0.08, self.view.frame.size.width, HeighZ * 0.045);
//    
//    [self.moreButton setBackgroundImage:[UIImage imageNamed:@"hott.png"] forState:UIControlStateNormal];
//    
//    [self.moreButton setBackgroundColor:[UIColor whiteColor]];
//    [self.moreButton addSubview:self.imageV];
//    [self.moreButton addTarget:self action:@selector(moreButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
//    [myCollectionView addSubview:self.moreButton];
    
    
    
    
    
    // 实现第三方滑动
    self.homeArray = [NSMutableArray array];
    self.notesModelArray = [NSMutableArray array];
    self.colorIndex = 0;
  
//    self.photoButton.frame = CGRectMake(0, HeighZ * 0.045, self.view.frame.size.width, HeighZ *0.045);
//    self.photoButton.backgroundColor = [UIColor redColor];
    
    self.photoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.photoButton.frame = CGRectMake(0, HeighZ * 0.6 / 6 * 0.5 * 0.5, self.view.frame.size.width, HeighZ * 0.6 / 6 * 0.5);
    self.photoButton.backgroundColor = [UIColor redColor];
    [self.photoButton addTarget:self action:@selector(morePhoto) forControlEvents:UIControlEventTouchUpInside];
    
    [self.photoButton setBackgroundImage:[UIImage imageNamed:@"more.png"] forState:UIControlStateNormal];
    [self.photoButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [myCollectionView addSubview:self.photoButton];
    self.myImageView = [[UIImageView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    
    self.aaaaa = NO;
    self.bbbbb = NO;
    
//      self.swipeableView = [[ZLSwipeableView alloc]initWithFrame:CGRectMake(WidthZ * 0.15, HeighZ * 0.14, self.view.frame.size.width - WidthZ * 0.3, self.view.frame.size.width - WidthZ * 0.3)];
//    self.swipeableView = [[ZLSwipeableView alloc]initWithFrame:CGRectMake(WidthZ * 0.15, HeighZ * 0.045 + HeighZ *0.045 + HeighZ * 0.015, self.view.frame.size.width - WidthZ * 0.3, self.view.frame.size.width - WidthZ * 0.3)];
    
    // 图片窗
    self.swipeableView = [[ZLSwipeableView alloc]initWithFrame:CGRectMake(WidthZ * 0.15, self.photoButton.frame.size.height + self.photoButton.frame.origin.y + HeighZ * 0.6 / 6 * 0.5 * 0.5, self.view.frame.size.width - WidthZ * 0.3, HeighZ * 0.6 / 6 * 4)];
//    [self.view addSubview:self.swipeableView];
    self.swipeableView.backgroundColor = [UIColor whiteColor];
    
//    self.swipeableView.center = CGPointMake(HeighZ / 3, HeighZ / 3);
    
    
    self.moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [self.moreButton setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
    
    
    //    self.moreButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    //    self.moreButton.contentEdgeInsets = UIEdgeInsetsMake( 0, 0, 0, 20);
    
//    self.moreButton.frame = CGRectMake(0, flowLayout.sectionInset.top - HeighZ * 0.08, self.view.frame.size.width, HeighZ * 0.045);
    //    [self.moreButton addSubview:hotlabel];
    [self.moreButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//     self.moreButton.frame = CGRectMake(0, HeighZ * 0.045 + HeighZ *0.045 + HeighZ * 0.045 + self.view.frame.size.width - WidthZ * 0.3 , self.view.frame.size.width, HeighZ * 0.045);
    
    
    self.moreButton.frame = CGRectMake(0, self.swipeableView.frame.size.height + self.swipeableView.frame.origin.y + HeighZ * 0.6 / 6 * 0.5 * 0.5, self.view.frame.size.width, HeighZ * 0.6 / 6 * 0.5);
    
    [self.moreButton setBackgroundImage:[UIImage imageNamed:@"hott.png"] forState:UIControlStateNormal];
    
    [self.moreButton setBackgroundColor:[UIColor whiteColor]];
    [self.moreButton addSubview:self.imageV];
    [self.moreButton addTarget:self action:@selector(moreButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 小菊花
    
    
    UIActivityIndicatorView *testActivityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    testActivityIndicator.center = CGPointMake(self.view.frame.size.width / 2.0, (self.view.frame.size.height - 113) / 2);//只能设置中心，不能设置大小
    [self.view addSubview:testActivityIndicator];
    [testActivityIndicator startAnimating]; // 开始旋转
    
    
    
//    testActivityIndicator.backgroundColor = [UIColor lightGrayColor];
   
//    if (1) {
//        [testActivityIndicator removeFromSuperview];
//    }
    
    
    
    
    // 图片窗底图
    self.pageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, self.swipeableView.frame.size.width, self.swipeableView.frame.size.width)];
//    UILabel *labelq = [[UILabel alloc]initWithFrame:CGRectMake(90, self.swipeableView.frame.size.width - 20, self.swipeableView.frame.size.width, 20)];
//    labelq.text = @"点击查看更多";
//    labelq.textColor = [UIColor blackColor];
//    labelq.font = [UIFont systemFontOfSize:20];
    
    
    
//    [self.pageView addSubview:labelq];
    self.pageView.image = [UIImage imageNamed:@"imagePhoto_meitu_1.png"];
    
//    [myCollectionView addSubview:self.swipeableView];
    UITapGestureRecognizer *Pagetap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(PageTapAction)];


    [self.swipeableView addGestureRecognizer:Pagetap];

    self.page = 0;

   
    // 主页面铺建
    self.titleButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.titleButton setTitle:@"" forState:UIControlStateNormal];
    [self.titleButton addTarget:self action:@selector(PushNotes) forControlEvents:UIControlEventTouchUpInside];
    
    
    // 请求主页数据
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];

    
    NSString *url_string = [NSString stringWithFormat:@"http://api.breadtrip.com/featured/photos/?start=0&count=12"];
//   http://api.breadtrip.com/featured/photos/?start=0&count=12
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
     
        NSMutableDictionary *dic = responseObject;
        [[DataHandle sharDataBaseHandle]dropTableb];
        [[DataHandle sharDataBaseHandle]creatDBb];
        
        
        NSMutableArray *array = [dic objectForKey:@"items"];
        for (NSMutableDictionary *dic2 in array) {
            TravelNotesHomePageModel *model = [[TravelNotesHomePageModel alloc]init];
            model.photo_s = [dic2 objectForKey:@"photo_w640"];
            model.address = [dic2 objectForKey:@"name"];
            model.detailId = [dic2 objectForKey:@"trip_id"];


            [[DataHandle sharDataBaseHandle]insertTravelphoto:model];
            
            [self.notesModelArray addObject:model];
            
        }
//        NSMutableArray *array = [dic objectForKey:@"elements"];
//        NSMutableDictionary *dic1 = [array objectAtIndex:1];
//        NSMutableArray *array1 = [dic1 objectForKey:@"data"];
//        for (NSMutableDictionary *dic2 in array1) {
//            TravelNotesModel *model = [[TravelNotesModel alloc]init];
//            [model setValuesForKeysWithDictionary:dic2];
//            [self.notesModelArray addObject:model];
////            NSLog(@"---- %@", model.cover_image_default);
////            NSLog(@"()()()() %ld", self.notesModelArray.count);
//        }
        
        [myCollectionView reloadData];
        self.swipeableView.dataSource = self;
         self.swipeableView.delegate = self;
        // 刷新
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
        
        for (int i = 0; i < 12; i++) {
            
            [self.notesModelArray addObject:[[[DataHandle sharDataBaseHandle] selectAllStudentb] objectAtIndex:i]];
            
        }
        
        [myCollectionView reloadData];
//        self.swipeableView.delegate = self;
        self.swipeableView.dataSource = self;

    }];

    
    
    AFNetworkReachabilityManager *netWorkManagera = [AFNetworkReachabilityManager sharedManager];
    
    
    NSString *url_stringa = [NSString stringWithFormat:@"http://api.breadtrip.com/featured/"];
    //   http://api.breadtrip.com/featured/photos/?start=0&count=12
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    
    AFHTTPRequestOperationManager* managera = [AFHTTPRequestOperationManager manager];
    managera.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [managera GET:url_stringa parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManagera stopMonitoring];
        //        NSLog(@"使用AFN进行get请求 ===  %@",responseObject);
        
        [testActivityIndicator removeFromSuperview];
        [myCollectionView addSubview:self.moreButton];
        [myCollectionView addSubview:self.photoButton];
        [myCollectionView addSubview:self.swipeableView];
//
        [[DataHandle sharDataBaseHandle]dropTable];
        [[DataHandle sharDataBaseHandle]creatDB];

        
        NSMutableDictionary *dic = responseObject;
        
        
        
        NSMutableArray *array = [dic objectForKey:@"elements"];
        NSMutableDictionary *dic1 = [array objectAtIndex:1];
        NSMutableArray *array1 = [dic1 objectForKey:@"data"];
        for (NSMutableDictionary *dic2 in array1) {
            TravelHomeModel *modele = [[TravelHomeModel alloc]init];
            modele.name = [dic2 objectForKey:@"name"];
            modele.popular_place_str = [dic2 objectForKey:@"popular_place_str"];
            modele.cover_image = [dic2 objectForKey:@"cover_image_w640"];
            modele.detailid = [dic2 objectForKey:@"id"];
            NSMutableDictionary *dic3 = [dic2 objectForKey:@"user"];
            modele.userName = [dic3 objectForKey:@"name"];
            modele.avatar_s = [dic3 objectForKey:@"avatar_m"];
            
            [[DataHandle sharDataBaseHandle]insertTravelNotes:modele];
            
            [self.homeArray addObject:modele];
        }
            //            NSLog(@"---- %@", [NSString stringWithFormat:@"%@", [dic3 objectForKey:@"address"]]);
            
            
//            [self.notesModelArray addObject:model];
        
        
     
        [myCollectionView reloadData];
        
//        self.swipeableView.dataSource = self;
//        self.swipeableView.delegate = self;
        // 刷新
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
        
        NSLog(@"失败==== %@",error);
        
        
        for (int i = 0; i < 5; i++) {
            
            [self.homeArray addObject:[[[DataHandle sharDataBaseHandle] selectAllStudent] objectAtIndex:i]];
            
        }
        
        
        
        [testActivityIndicator removeFromSuperview];
        [myCollectionView addSubview:self.swipeableView];
        [myCollectionView addSubview:self.moreButton];
        [myCollectionView addSubview:self.photoButton];
        
        
    }];
    
    
    
    NSLog(@"wo s pian yi liang    %f", myCollectionView.contentSize.height);

    NSLog(@"wo s zuo biao %f", myCollectionView.contentOffset.y);
//    if (myCollectionView.contentOffset.y >400) {
//        
//        
//        
//    }
    
    
    
    
    
    
}

-(void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        self.colorIndex = 0;
        self.page = 0;
        [self.swipeableView discardAllSwipeableViews];
        [self.swipeableView loadNextSwipeableViewsIfNeeded];
        [self.pageView removeFromSuperview];

    }
    
}

//- (void)reloadPhoto
//{
//    self.colorIndex = 0;
//    [self.swipeableView discardAllSwipeableViews];
//    [self.swipeableView loadNextSwipeableViewsIfNeeded];
//    
//    
//}

-(void)PushNotes
{
    
//    http://api.breadtrip.com/featured/photos/?start=0&count=12
    
}

- (void)viewDidLayoutSubviews {
    // Required Data Source
    
}

- (void)PageTapAction
{
    TravelPhotoPageViewController *pageVC = [[TravelPhotoPageViewController alloc]init];
    [self.navigationController pushViewController:pageVC animated:YES];
    NSLog(@"aaa");
    
}




#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet
clickedButtonAtIndex:(NSInteger)buttonIndex {
    self.loadCardFromXib = buttonIndex == 1;
    
    self.colorIndex = 0;
    [self.swipeableView discardAllSwipeableViews];
    [self.swipeableView loadNextSwipeableViewsIfNeeded];
}

#pragma mark - ZLSwipeableViewDelegate
- (void)swipeableView:(ZLSwipeableView *)swipeableView
         didSwipeView:(UIView *)view
          inDirection:(ZLSwipeableViewDirection)direction {
    NSLog(@"did swipe in direction: %zd", direction);
    self.page++;
//    NSLog(@"page, %ld", self.page);
}

- (void)swipeableView:(ZLSwipeableView *)swipeableView
       didCancelSwipe:(UIView *)view {
//    NSLog(@"did cancel swipe");
}

- (void)swipeableView:(ZLSwipeableView *)swipeableView
    didStartSwipingView:(UIView *)view
             atLocation:(CGPoint)location {
//    NSLog(@"did start swiping at location: x %f, y %f", location.x, location.y);
}

- (void)swipeableView:(ZLSwipeableView *)swipeableView
          swipingView:(UIView *)view
           atLocation:(CGPoint)location
          translation:(CGPoint)translation {
//    NSLog(@"swiping at location: x %f, y %f, translation: x %f, y %f",
//          location.x, location.y, translation.x, translation.y);
//    self.page++;
}

- (void)swipeableView:(ZLSwipeableView *)swipeableView
    didEndSwipingView:(UIView *)view
           atLocation:(CGPoint)location {
    
//    NSLog(@"did end swiping at location: x %f, y %f", location.x, location.y);
}

#pragma mark - ZLSwipeableViewDataSource

- (UIView *)nextViewForSwipeableView:(ZLSwipeableView *)swipeableView {
   
    if (self.colorIndex < self.notesModelArray.count) {
//        NSLog(@"(((((((( %ld",self.notesModelArray.count);
        CardView *view = [[CardView alloc] initWithFrame:CGRectMake(0, 0, swipeableView.frame.size.width, swipeableView.frame.size.width)];
        
        [self.view bringSubviewToFront:view];
    
        
        UIImageView *imagev = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, swipeableView.frame.size.width, swipeableView.frame.size.width)];
        NSURL *url = [NSURL URLWithString:[[self.notesModelArray objectAtIndex:self.colorIndex] photo_s]];
        imagev.layer.cornerRadius = 5;
        imagev.layer.masksToBounds = YES;
        [imagev sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"imagePhoto.png"]];

    
        self.deId = [[self.notesModelArray objectAtIndex:self.page ] detailId];
        NSLog(@"deid page %d", self.page);
       
        
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];

        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(5, 150, 100, 20)];
        label.text = @"aaa";
        [view addSubview:label];
        [view addGestureRecognizer:tap];
        [view addSubview:imagev];
        
        [self.view addSubview:view];
        self.colorIndex++;
        return view;
    }
    else{
        NSLog(@"wzoubuzou");
        self.colorIndex++;
        NSLog(@"self.colrindel %d", self.colorIndex);
        if (self.colorIndex == 16) {
            
            [self.swipeableView addSubview:self.pageView];
            
        }

        return nil;
    }
}


- (void)tapAction
{
    
    TravelNotesDetailViewController *detailVC = [[TravelNotesDetailViewController alloc]init];
    NSLog(@"self. id%@", self.deId);
    detailVC.myId = self.deId;
    detailVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:detailVC animated:YES];
    
    
}




- (void)moreButtonAction
{
    TravelNotesViewController *travela = [[TravelNotesViewController alloc]init];
    [self.navigationController pushViewController:travela animated:YES];
    
}

- (void)morePhoto
{
    
    TravelPhotoPageViewController *photoPage = [[TravelPhotoPageViewController alloc]init];
    [self.navigationController pushViewController:photoPage animated:YES];
}










- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
   
    if (kind == UICollectionElementKindSectionHeader) {
  
        UICollectionReusableView *reuseablieView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        reuseablieView.backgroundColor = [UIColor blackColor];

        reuseablieView.userInteractionEnabled = YES;
        
        

        return reuseablieView;
    }

    return nil;
    
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.homeArray.count;
    
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    
    return 1;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TravelNotesHomePageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor redColor];
    if (self.homeArray.count == 5) {
        
        cell.model = [self.homeArray objectAtIndex:indexPath.row];
    }
    if (indexPath.row == 0) {
        
    }
    
    
    return cell;
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.homeArray != 0) {
        
        TravelNotesDetailViewController *detailVC = [[TravelNotesDetailViewController alloc]init];
        detailVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
        detailVC.myId = [[self.homeArray objectAtIndex:indexPath.row] detailid];
    }
    
    
}


//- (void)didReceiveMemoryWarning {
//    [super didReceiveMemoryWarning];
//    // Dispose of any resources that can be recreated.
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
